#include "Url.hpp"
#include "String.hpp"

#include <cassert>

using namespace std;

Url::Url() : mPort(DEFAULT_HTTP_PORT) {}

bool
Url::ParseUrl(const string& crUrlKey)
{
    bool is_good_status = true;
    if (crUrlKey.empty()) {
        is_good_status = false;
    } else {
        mOrginUrl = crUrlKey;
        String::Str2Lower(mOrginUrl);

        is_good_status = ParseScheme();

        if (is_good_status == true) {
            is_good_status = ParseHost();
        }
    }
    return is_good_status;
}

bool
Url::ParseScheme()
{
    bool is_valid_sheme = true;
    if (mOrginUrl.substr(0, 7) != "http://") {
        is_valid_sheme = false;
    }
    return is_valid_sheme;
}

bool
Url::ParseHost()
{
    bool host_is_valid = true;

    string::size_type host_start_address;
    string::size_type host_end_address;
    string::size_type comma_in_address;

    host_start_address = mOrginUrl.find("//");
    assert(host_start_address != string::npos);
    host_start_address += 2;

    host_end_address = mOrginUrl.find("/", host_start_address);
    comma_in_address = mOrginUrl.find(":", host_start_address);

    if (host_end_address == string::npos) { // eg: http://www.pku.edu.cn(:8080)
        if (comma_in_address != string::npos) {
            mHost = mOrginUrl.substr(host_start_address,
                                     comma_in_address - host_start_address);
            mPort = atoi(mOrginUrl.substr(comma_in_address+1).c_str());
        } else {
            mHost = mOrginUrl.substr(host_start_address);
        }
        mPath = "/";
    } else {                    // eg: http://www.pku.edu.cn/(index.html)
        if (comma_in_address != string::npos) {
            mHost = mOrginUrl.substr(host_start_address,
                                     comma_in_address - host_start_address);
            mPort = atoi(mOrginUrl.substr(comma_in_address+1).c_str());
        } else {
            mHost = mOrginUrl.substr(host_start_address,
                                     host_end_address - host_start_address);
        }
        mPath = mOrginUrl.substr(host_end_address);
    }

    if (mHost.empty()) {
        host_is_valid = false;
    }
    return host_is_valid;
}

